class wxrequest{
  defaults={
    baseURL:"",
    url:"",
    data:null,
    method:"GET",
    header:{
      "Content-type":"application/json"
    },
    timeout:60000
  }
  // 拦截器
  interceptors={
    request:(config)=>{return config},
    response:(response)=>{return response}
  }
  queqe=[]
  timeid
  isloading=true
  constructor(params={}){
    this.defaults=Object.assign({},this.defaults,params)
  }
  request(options){
    // 合并参数
    options.url=this.defaults.baseURL+options.url
    options={...this.defaults,...options}
     // 每次发送请求显示loading
     if(this.isloading && options.method !=="upload"){
      this.queqe.length==0 && wx.showLoading({})
      this.queqe.push("request")
    }
    // 将options一起发送到请求拦截器
    options=this.interceptors.request(options)
    return new Promise((resolve,reject)=>{
      if(options.method=="upload"){
        wx.uploadFile({
          ...options,
          success:(res)=>{
            res.data=JSON.parse(res.data)
            const mergeres=Object.assign({},res,{
              config:options,
              issuccess:true
            })
            resolve(this.interceptors.response(mergeres))
          },
          fail:(error)=>{
            const mergeres=Object.assign({},error,{
              config:options,
              issuccess:false
            })
            reject(this.interceptors.response(mergeres))
          }
        })
      }else{
        wx.request({
          ...options,
          success:(res)=>{
            const mergeres=Object.assign({},res,{config:options,issuccess:true})
            resolve(this.interceptors.response(mergeres))
          },
          fail:(error)=>{
            const mergeerror=Object.assign({},error,{config:options,issuccess:false})
            reject(this.interceptors.response(mergeerror))
          },
          complete:()=>{
           if(this.isloading){
              // 无论请求是否发送成功都关闭loading
            this.queqe.pop()
            this.queqe.length==0 && this.queqe.push("requst")
  
            this.timeid= setTimeout(() => {
              this.queqe.pop()
              this.queqe.length==0 && wx.hideLoading()
              clearTimeout(this.timeid)
            }, 10);
            
           }
          }
        })
      }
    })
  }
  get(url,data={},config={}){
   return this.request(Object.assign({url,data,method:"GET"},config))
  }
  delete(url,data={},config={}){
   return this.request(Object.assign({url,data,method:"DELETE"},config))
  }
  post(url,data={},config={}){
   return this.request(Object.assign({url,data,method:"POST"},config))
  }
  put(url,data={},config={}){
   return this.request(Object.assign({url,data,method:"PUT"},config))
  }
  all(...promise){
    return Promise.all(promise)
  }
  upload(url,filePath,name="file",config={}){
    return this.request(Object.assign({url,filePath,name,method:"upload"},config))
  }
}
export default wxrequest